package com.gopay.cashier.web.controller;

import java.io.IOException;
import java.io.Serializable;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.cashier.service.BisBankInfoService;
import com.gopay.common.domain.bis.BisBankInfoMain;

/**
 * 打印银行图标
 * 
 * @author zhanglei
 * @version 1.0 2012-7-17
 */
@Controller
public class BankIconController extends BaseController {
    protected final static Logger logger = LoggerFactory.getLogger(BankIconController.class);
    @Autowired
    private BisBankInfoService bankInfoService;
    @Resource(name = "bankIconCache")
    private Cache cache;

    @RequestMapping(value = "/BankIcon/{bankCode}.jpeg")
    public ModelAndView execute(HttpServletRequest request, HttpServletResponse response, @PathVariable String bankCode)
            throws IOException {
//        logger.info("[execute]bankCode:{}", bankCode);
        byte[] bankPic = null;
        BisBankInfoMain bank = null;
        try {
            Element bankElement = (Element) cache.get(bankCode.toUpperCase());
            if (bankElement == null) {
                bank = this.bankInfoService.getByCode(bankCode.toUpperCase());
                if(bank != null && bank.getBankPic() != null){
                	bankPic = new byte[(int) bank.getBankPic().length()];
                    bank.getBankPic().getBinaryStream().read(bankPic);
                    Element element = new Element(bank.getBankCode(), (Serializable) bankPic);
                    cache.put(element);
                }else{
                	logger.error("can't load pic for bank "+bankCode);
                }
            } else {
                bankPic = (byte[]) bankElement.getValue();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        ServletOutputStream op = null;
        try {
            if (bankPic != null) {
                op = response.getOutputStream();
                op.write(bankPic, 0, bankPic.length);
                op.flush();
                response.flushBuffer();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (op != null) {
                op.close();
                op = null;
            }
        }
        return null;
    }
}
